#coding: utf-8 or # -*- coding: utf-8 -*-
import os
import json
from flask import Flask
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy import (create_engine, MetaData, Column, Integer, String)
from sqlalchemy import func
from sqlalchemy.sql.expression import and_, or_
from sqlalchemy import Table, Column, Integer, String, Text, DateTime, MetaData, ForeignKey, Boolean, types, Numeric
from datetime import datetime, date,time
from sqlca import get_Session
from json_exa import ret_json, row3dict
from login import infor_worker
from get_cardinfo import card_ticket_sum,parse_track
from pos_check import token_check,pos_en
import sys
from card_app_log import app_log
from card_sale_day import T_LZ_SALE_APP
from  card_trade_confirm import T_LZ_CARD_SALE_RETURN




def check(data_list):
	list_w = data_list.split('&')
	print list_w
	json_list = {}
	for lst in list_w:
		li = lst.split('=',1)
		json_list[li[0]] = li[1]
	token_c = token_check(json_list['key'])
	print token_c
	if token_c['code'] != '10':
		return json.dumps(token_c, ensure_ascii=False)
	oper = token_c['operator']
	posen = pos_en(json_list['posno'])
	if posen['code'] != '10':
		return json.dumps(posen, ensure_ascii=False)
	old_bill = json_list["old_bill"]
	session = get_Session()()
	ll_count = session.query(func.count(1)).filter(T_LZ_SALE_APP.bill==old_bill).scalar()
	if ll_count == 0:
		ls_msg = '订单号无效'
		return json.dumps({"code": "72", "error": ls_msg},ensure_ascii=False)
	query = session.query(T_LZ_SALE_APP).filter(T_LZ_SALE_APP.bill==old_bill).scalar()
	if query.MONEY < 0:
		ls_msg = '此单为退款交易,不能再次退款'
		return json.dumps({"code": "72", "error": ls_msg},ensure_ascii=False)

	ll_count = session.query(func.count(1)).filter(T_LZ_CARD_SALE_RETURN.C_RETREATE_NO==old_bill).scalar()
	if ll_count > 0:
		ls_msg = '订单号无效,不能再次退款'
		return json.dumps({"code": "72", "error": ls_msg},ensure_ascii=False)   

	lde_money = str(query.MONEY)
	ls_msg = 'succeed'
	return json.dumps({"code": "10", "error": ls_msg,"money":lde_money },ensure_ascii=False)

def print_ret(data_list):
	app_log(data_list,'print')
	list_w = data_list.split('&')
	print list_w
	json_list = {}
	for lst in list_w:
		li = lst.split('=',1)
		json_list[li[0]] = li[1]
	token_c = token_check(json_list['key'])
	print token_c
	if token_c['code'] != '10':
		return json.dumps(token_c, ensure_ascii=False)
	oper = token_c['operator']
	posen = pos_en(json_list['posno'])
	if posen['code'] != '10':
		return json.dumps(posen, ensure_ascii=False)
	print '==========================='
	print json_list
	old_bill = json_list["bill_no"]
	session = get_Session()()
	ls_dt =  session.execute(
        "select to_char(sysdate ,'yyyy-mm-dd') from DUAL").first()[0]
	print old_bill
	if old_bill == '*':
		print "**************"
		old_bill = session.execute(
		    "select max(bill) from T_LZ_SALE_APP where posno =:pos_no ",{"pos_no":json_list['posno']}).first()[0]
		print old_bill
	elif len(old_bill) == 5:
		ls_retail = old_bill
		ll_count = session.execute(
				    "select count(*) from T_LZ_CARD_SALE_DAY where c_pos_id =:pos_no and c_dt = :ls_dt and C_RETAIL_ID = :ls_retail",\
				    {"pos_no":json_list['posno'],"ls_dt":ls_dt,"ls_retail":ls_retail}).first()[0]
		if ll_count == 0:
			ls_msg = '订单号无效1'
			return json.dumps({"code": "72", "error": ls_msg},ensure_ascii=False) 

		old_bill = session.execute(
		    "select to_char(d_retail_time,'yymmdd')||c_pos_id||C_RETAIL_ID from T_LZ_CARD_SALE_DAY where c_pos_id =:pos_no and c_dt = :ls_dt and C_RETAIL_ID = :ls_retail",\
		    {"pos_no":json_list['posno'],"ls_dt":ls_dt,"ls_retail":ls_retail}).first()[0]
		if old_bill == '' or old_bill == None :
			ls_msg = '订单号无效1'
			return json.dumps({"code": "72", "error": ls_msg},ensure_ascii=False) 

	ll_count = session.query(func.count(1)).filter(T_LZ_SALE_APP.bill==old_bill).scalar()
	if ll_count == 0:
		ls_msg = '订单号无效'
		return json.dumps({"code": "72", "error": ls_msg},ensure_ascii=False)
	query = session.query(T_LZ_SALE_APP).filter(T_LZ_SALE_APP.bill==old_bill).scalar()
	print query.N_MONEY_BALANCE
	lde_banance = str(query.N_MONEY_BALANCE)
	posno =  query.posno
	billno = old_bill
	lde_money = query.MONEY
	ls_card = query.CARD_ID
	oper = query.cashier_id
	dt = query.dt
	if lde_money > 0:
		type = '消费'
	else:
		type = '退货'
	money = str(lde_money)
	ls_msg = 'succeed'
	print_str = '''
       红博商业    
            复制联 
终端机号 %s    
操作员号 %s 
交易时间 %s
订 单 号 %s
交易类型 %s
交易金额 %s
交易卡号 %s
余额     %s
持卡人签字
__________________
持卡人已接受此单据
金额的有关商品
	    '''%(posno,oper,dt,billno,type,money,ls_card,lde_banance)
	session.close()
	return json.dumps({"code": "10", "error": ls_msg,"print":print_str },ensure_ascii=False)




def group_sum(data_list):
	app_log(data_list,'group_sum')
	list_w = data_list.split('&')
	print list_w
	json_list = {}
	for lst in list_w:
		li = lst.split('=',1)
		json_list[li[0]] = li[1]
	token_c = token_check(json_list['key'])
	print token_c
	if token_c['code'] != '10':
		return json.dumps(token_c, ensure_ascii=False)
	oper = token_c['operator']
	posen = pos_en(json_list['posno'])
	if posen['code'] != '10':
		return json.dumps(posen, ensure_ascii=False)
	print '==========================='
	print json_list
	ls_pos = json_list['posno']
	print ls_pos
	session = get_Session()()
	ll_count =  session.execute("select count(*)  from V_T_LZ_SALE_SUM where c_pos_id =:pos_no ",{"pos_no":ls_pos}).first()
	if ll_count[0] == 0:
		ls_msg = '该终端今天无交易记录'
		return json.dumps({"code": "72", "error": ls_msg},ensure_ascii=False)

	query =session.execute("select C_DT, C_POS_ID, MONEY ,sum_num, money_ret ,sum_mon  from V_T_LZ_SALE_SUM where c_pos_id =:pos_no ",{"pos_no":ls_pos}).first()
	
	dt = query[0]
	posno = query[1]
	money = query[2]
	ls_num = query[3]
	money_ret = query[4]
	sum_mon = query[5]
	#,dt,ls_num,money,money_ret,sum_mon
	ls_msg = 'succeed'
	print_str = '''
       红博商业    
            汇总联 
终端机号 %s    
交易日期 %s
交易笔数 %s
消费金额 %s
退货金额 %s
合计金额 %s
	    '''%(posno,dt,ls_num,money,money_ret,sum_mon)
	session.close()
	return json.dumps({"code": "10", "error": ls_msg,"print":print_str },ensure_ascii=False)	



# session = get_Session()()
# ls_pos = '7108'
# ls_group_str =  session.execute("select C_DT, C_POS_ID, MONEY ,sum_num, money_ret ,sum_mon  from V_T_LZ_SALE_SUM where c_pos_id =:pos_no ",{"pos_no":ls_pos}).first()


#  # "select to_char(d_retail_time,'yymmdd')||c_pos_id||C_RETAIL_ID from T_LZ_CARD_SALE_DAY where c_pos_id =:pos_no and c_dt = :ls_dt and C_RETAIL_ID = :ls_retail",\
# 	# 	    {"pos_no":json_list['posno'],"ls_dt":ls_dt,"ls_retail":ls_retail}).first()[0]

# print ls_group_str
# print ls_group_str[0]
# print ls_group_str[1]
# # for i in ls_group_str:
# # 	print i


# query =  session.execute("select C_DT, C_POS_ID, MONEY ,sum_num, money_ret ,sum_mon  from V_T_LZ_SALE_SUM where c_pos_id =:pos_no ",{"pos_no":ls_pos}).first()
# dt = query[0]
# posno = query[1]
# money = query[2]
# ls_num = query[3]
# money_ret = query[4]
# sum_mon = query[5]
# #,dt,ls_num,money,money_ret,sum_mon
# ls_msg = 'succeed'
# print_str = '''
#        红博商业    
#             汇总联 
# 终端机号 %s    
# 交易日期 %s
# 交易笔数 %s
# 消费金额 %s
# 退货金额 %s
# 合计金额 %s
# 	    '''%(posno,dt,ls_num,money,money_ret,sum_mon)
# print print_str
# print json.dumps({"code": "10", "error": ls_msg,"print":print_str },ensure_ascii=False)	
# ls_srt = 'req_type=Summary&posno=7102&key=2016-03-0511:03:55,7102,70035'
# print group_sum(ls_srt)